package com.cya.lotterysystem.service.activityStatus.impl;

import com.cya.lotterysystem.common.errcode.ServiceErrorCodeConstans;
import com.cya.lotterysystem.common.exception.ServiceException;
import com.cya.lotterysystem.service.ActivityService;
import com.cya.lotterysystem.service.activityStatus.ActivityStatusManager;
import com.cya.lotterysystem.service.activityStatus.operator.AbstractActivityOperator;
import com.cya.lotterysystem.service.dto.ConverActivityStatusDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author ：陈奕安（3048279304@qq.com）
 * @date ：Created in 2025/11/7 11:52
 * @description：责任链模式
 * @modified By：
 * @version:
 */
@Slf4j
@Service
public class ActivityStatusManagerImpl implements ActivityStatusManager
{
    @Autowired
    private final Map<String, AbstractActivityOperator> operatorMap=new HashMap<>();

    @Autowired
    private ActivityService activityService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handlerEvent(ConverActivityStatusDTO converActivityStatusDTO) {
        // 问题：1.活动状态扭转有依赖性，导致代码维护性差
        //2.状态扭转套件可能会扩展，当前写法扩展性差，维护性差
        //3. 代码灵活性差，扩展性，维护性差
        //解决方案：设计模式，（责任链模式，策略模式）


        if (CollectionUtils.isEmpty(operatorMap)){
            log.warn("operatorMap为空！");
            return;
        }
        //map：<String,AbstractActivityOperator>
        Map<String,AbstractActivityOperator> currMap=new HashMap<>(operatorMap);
        Boolean update=false;


//        先处理：人员，奖品
      update=  processConverStatus(converActivityStatusDTO,currMap,1);

//        后处理活动

            update=  processConverStatus(converActivityStatusDTO,currMap,2)||update;

//        更新缓存
        if (update){
            activityService.cacheActivity(converActivityStatusDTO.getActivityId());

        }

    }

    @Override
    public void rollbackhandlerEvent(ConverActivityStatusDTO converActivityStatusDTO) {

        //operatorMap:活动，奖品，人员
        for (AbstractActivityOperator operator:operatorMap.values()){
            operator.convert(converActivityStatusDTO);
        }
        //缓存更新
        activityService.cacheActivity(converActivityStatusDTO.getActivityId());



    }

    /**
     * 扭转状态
     * @param converActivityStatusDTO
     * @param currMap
     * @param sequence
     * @return
     */
    private Boolean processConverStatus(ConverActivityStatusDTO converActivityStatusDTO, Map<String, AbstractActivityOperator> currMap, int sequence) {
//遍历map
        Boolean updata=false;
     Iterator< Map.Entry<String,AbstractActivityOperator>> iterator= currMap.entrySet().iterator();
     while ((iterator.hasNext())){
         AbstractActivityOperator operator = iterator.next().getValue();
//        operator是否需要转换

            if (operator.sequence()!=sequence
            ||!operator.needConvert(converActivityStatusDTO)){
                continue;

            }
//        需要转换：转换

            if (!operator.convert(converActivityStatusDTO)){
                log.error("{}转换失败！",iterator.getClass().getName());
                throw new ServiceException(ServiceErrorCodeConstans.ACTIVITY_STATUS_CONVERT_ERROE);
            }
//      currmap删除当前operator

            iterator.remove();
            updata=true;
     }



//        返回
        return updata;

    }
}